package com.boge.auth.serviceImpl.dept;

import com.boge.auth.model.dao.mappers.SysDeptMapper;
import com.boge.auth.model.entity.SysDept;
import com.boge.auth.param.SysDeptParam;
import com.boge.auth.service.dept.SysDeptService;
import com.boge.auth.util.LevelUtil;
import com.boge.common.BeanValidator;
import com.boge.exception.ParamException;
import com.boge.util.ParamUtil;
import com.google.common.base.Preconditions;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.rmi.UnexpectedException;
import java.util.Date;
import java.util.List;

@Slf4j
@Log4j
@Service
public class SysDeptServiceImpl implements SysDeptService {

    @Resource
    SysDeptMapper sysDeptMapper;

    private boolean checkExist(Integer parentId, String deptName, Integer deptId) {
        return sysDeptMapper.countByNameAndParentId(parentId, deptName, deptId) > 0;
    }

    private String getLevel(Integer deptId) {
        SysDept sysDept = sysDeptMapper.selectByPrimaryKey(deptId);
        if (sysDept == null) {
            return null;
        }
        return sysDept.getLevel();
    }

    @Transactional
    private void updateWithChild(SysDept before, SysDept after) {
        //TODO:为何level会改变
        String oldLevelPrefix = before.getLevel();
        String newLevelPrefix = after.getLevel();
        if (!oldLevelPrefix.equals(newLevelPrefix)) {
            List<SysDept> deptList = sysDeptMapper.getChildDeptListByLevel(before.getLevel());
            if (CollectionUtils.isNotEmpty(deptList)) {
                for (SysDept dept : deptList) {
                    String level = dept.getLevel();
                    //TODO:获取的所有部门的level不是都以oldLevel开头的吗
                    if (level.indexOf(oldLevelPrefix) == 0) {
                        level = newLevelPrefix + level.substring(oldLevelPrefix.length());
                        dept.setLevel(level);
                    }
                }
                sysDeptMapper.batchUpdateLevel(deptList);
            }
        }

        sysDeptMapper.updateByPrimaryKeySelective(after);

    }

    @Override
    public void addSysDept(SysDeptParam sysDeptParam) {
        BeanValidator.check(sysDeptParam);
        if (checkExist(sysDeptParam.getParentId(), sysDeptParam.getName(), sysDeptParam.getId())) {
            throw new ParamException("同一层级下存在相同部门！");
        }//TODO:sdss
        SysDept sysDept = SysDept.builder().name(sysDeptParam.getName()).parentId(sysDeptParam.getParentId())
                .seq(sysDeptParam.getSeq()).remark(sysDeptParam.getRemark()).build();
        String parentLevel = getLevel(sysDeptParam.getParentId());
        //level通过计算得到，所以不直接使用param从前端传值
        String level = LevelUtil.calculateLevel(parentLevel, sysDeptParam.getParentId());
        sysDept.setLevel(level);
        try {
            sysDept.setOperatorIp(InetAddress.getLocalHost().getHostAddress() + "");
        } catch (UnknownHostException e) {
            log.error(e + "");
        }
//        sysDept.setOperator(ParamUtil.user.getUserName());
        sysDept.setOperatorTime(new Date());
        sysDeptMapper.insertSelective(sysDept);
    }

    @Override
    public void updateSysDept(SysDeptParam param) {
        BeanValidator.check(param);
        //除此条外是否还有相同的部门
        if (checkExist(param.getParentId(), param.getName(), param.getId())) {
            throw new ParamException("同一层级下存在相同名称的部门");
        }
        SysDept before = sysDeptMapper.selectByPrimaryKey(param.getId());
        //TODO:错误信息如何抛出
        //防止被其他客户端删除
        Preconditions.checkNotNull(before, "待更新的部门已不存在");
        //TODO:重复

        SysDept after = SysDept.builder().id(param.getId()).name(param.getName()).parentId(param.getParentId())
                .seq(param.getSeq()).remark(param.getRemark()).build();
        after.setLevel(LevelUtil.calculateLevel(getLevel(param.getParentId()), param.getParentId()));
        try {
            after.setOperatorIp(InetAddress.getLocalHost().getHostAddress() + "");
        } catch (UnknownHostException e) {
            log.error(e + "");
        }
//        sysDept.setOperator(ParamUtil.user.getUserName());
        after.setOperatorTime(new Date());

        //如果该部门level改变，修改其子部门的level前缀
        //TODO:此方法上事务
        updateWithChild(before, after);

    }
}
